import { nanoid } from 'nanoid'
import OSS from 'ali-oss'
let bucketName= import.meta.env.VITE_APP_OSS_URL
let region=import.meta.env.VITE_APP_REGION
let accessKeyId=import.meta.env.VITE_APP_KEYID
let accessKeySecret=import.meta.env.VITE_APP_KEYSECRET


const OSSConfig = {
uploadHost:import.meta.env.VITE_APP_UPLOADHOST, //OSS上传地址
type: 'scs',
ossParams: {
  region: region,
  // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
  accessKeyId: accessKeyId,
  accessKeySecret: accessKeySecret,
  bucket: bucketName
}
};

function uploadOSS(file, fileName,dir) {
return new Promise(async (resolve, reject) => {
  var client = new OSS({
    region: OSSConfig.ossParams.region,
    accessKeyId: OSSConfig.ossParams.accessKeyId,
    accessKeySecret: OSSConfig.ossParams.accessKeySecret,
    bucket: OSSConfig.ossParams.bucket,
  });
  let timeSmap=new Date().getTime()
  // console.log(timeSmap);

  fileName=fileName.replace(/[^a-zA-Z0-9\u4e00-\u9fa5 ! ' ( ) * - . _ ~ ]/g, '');

  // console.log(fileName);

  let randomName = `${dir}${nanoid()}${fileName}`;

  // co(function* () {
  //   var result = yield client.multipartUpload(randomName, file);
  //   resolve(`${OSSConfig.uploadHost}/${result.name}`);
  // }).catch(function (err) {
  //   console.log(err);
  //   reject(err);
  // });

  var result = await client.multipartUpload(randomName, file);
  resolve(`${OSSConfig.uploadHost}/${result.name}`);





});
}


export { uploadOSS }
